package com.jt.flight.controller;

import com.jt.flight.domain.CityRelation;
import com.jt.flight.domain.Policy;
import com.jt.flight.model.Response;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * since 2015/10/30.
 */
@Controller
@RequestMapping("/policy")
public class PolicyController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(PolicyController.class);

    @RequestMapping
    public String index() {
        return "policy/list";
    }

    @RequestMapping("/add")
    @ResponseBody
    public Object add(Policy policy) {
        log.info("policy {}", policy);
        CityRelation cr = dao.fetch(CityRelation.class, Cnd.where("fromCode", "=", policy.getDepAirport()).and("toCode", "=", policy.getArrAirport()));
        if (cr == null) {
            cr = new CityRelation();
            cr.setFromCode(policy.getDepAirport());
            cr.setToCode(policy.getArrAirport());
            dao.insert(cr);
        }
        policy.setCityRelationId(cr.getId());
        dao.insert(policy);
        return Response.success("/policy/list", "");
    }

    @RequestMapping("/query")
    @ResponseBody
    public Object query(Pager pager) {
        List<Policy> policies = dao.query(Policy.class, null, pager);
        QueryResult result = new QueryResult();
        result.setList(policies);
        result.setPager(pager);
        return result;
    }


}
